package co.fitstart.admin.web.controller.report;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.demo2do.core.persistence.GenericDaoSupport;
import com.demo2do.core.support.Result;
import com.demo2do.core.utils.CollectionUtils;
import com.demo2do.core.utils.DateFormatUtils;
import com.demo2do.core.utils.DateUtils;
import com.demo2do.core.utils.JsonUtils;
import com.demo2do.core.utils.StringUtils;

import co.fitstart.admin.entity.report.TasteStatEveryDay;
import co.fitstart.admin.entity.report.TasteStatSingle;
import co.fitstart.admin.entity.security.Login;
import co.fitstart.admin.service.ReportService;
import co.fitstart.admin.web.interceptor.MenuSetting;
import co.fitstart.admin.web.resolver.Secure;
import co.fitstart.admin.web.view.ExcelTemplateView;
import co.fitstart.entity.taste.TasteSignUp;
import co.fitstart.entity.taste.TasteStat;

/**
 * 一元尝鲜统计
 * @author haiyan_xiao
 *
 */
@Controller
@RequestMapping("/taste-stat-reports")
@MenuSetting("menu-report")
public class TasteStatController {    
    @Autowired
    private ReportService reportService;
    
    @Autowired
    private GenericDaoSupport genericDaoSupport;
    
    @RequestMapping(value = "", method = RequestMethod.GET)
    @MenuSetting("submenu-taste-report")
    public ModelAndView list(@Secure Login login,
                             @RequestParam(value="period", required=false, defaultValue="hour") String period,
                             @RequestParam(value = "day", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd")Date day,
                             @RequestParam(value="source", required=false) String source) {
        
        ModelAndView modelAndView = new ModelAndView("report/taste-stat-report-list");
        
        Date now = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(now);
        
        if(day == null) {
            day = DateUtils.parseDate(DateFormatUtils.format(now, "yyyy-MM-dd"), "yyyy-MM-dd");
        }
        
        List<String> sources = reportService.listTasteStatSource();
        if(StringUtils.isBlank(source)) {
            source = null;
        }
        
        long questionNum = 0;
        long profileNum = 0;
        long orderNum = 0;
        
        if("hour".equals(period)) {
            
            if(source == null) {
                questionNum = reportService.countBMIQuestion(null, day, "day");
                profileNum = reportService.countTasteSignUp(null, day, "day");
                orderNum = reportService.countOrder(null, day, "day");
                
                List<TasteStatSingle> questionList = reportService.listTasteStatQuestion(day);
                List<TasteStatSingle> profileList = reportService.listTasteStatProfile(day);
                List<TasteStatSingle> orderList = reportService.listTasteStatOrder(day);
                
                modelAndView.addObject("questionList", CollectionUtils.constructMapValueFromList(questionList, "statInt"));
                modelAndView.addObject("profileList", CollectionUtils.constructMapValueFromList(profileList, "statInt"));
                modelAndView.addObject("orderList", CollectionUtils.constructMapValueFromList(orderList, "statInt"));
            } else {
                List<TasteStat> tasteStatList = reportService.listTasteStat(source, day);
                
                for(TasteStat tasteStat : tasteStatList) {
                    questionNum += tasteStat.getQuestionNum();
                    profileNum += tasteStat.getProfileNum();
                    orderNum += tasteStat.getOrderNum();
                }
                
                modelAndView.addObject("tasteStatList", CollectionUtils.constructMapValueFromList(tasteStatList, "statHour"));
            }
            
            
            modelAndView.addObject("maxHour", DateUtils.isSameDay(day, now) ? calendar.get(Calendar.HOUR_OF_DAY) : 23);
            modelAndView.addObject("profiles", reportService.listTasteSignUp(source, day));
        } else if("day".equals(period)) {
            if(source == null) {
                questionNum = reportService.countBMIQuestion(null, day, "month");
                profileNum = reportService.countTasteSignUp(null, day, "month");
                orderNum = reportService.countOrder(null, day, "month");
                
                List<TasteStatSingle> questionList = reportService.listMonthTasteStatQuestion(day);
                List<TasteStatSingle> profileList = reportService.listMonthTasteStatProfile(day);
                List<TasteStatSingle> orderList = reportService.listMonthTasteStatOrder(day);
                
                modelAndView.addObject("questionList", CollectionUtils.constructMapValueFromList(questionList, "statInt"));
                modelAndView.addObject("profileList", CollectionUtils.constructMapValueFromList(profileList, "statInt"));
                modelAndView.addObject("orderList", CollectionUtils.constructMapValueFromList(orderList, "statInt"));
            } else {
                List<TasteStatEveryDay> tasteStatList = reportService.listTasteStatEveryDay(source, day);
                
                for(TasteStatEveryDay tasteStat : tasteStatList) {
                    questionNum += tasteStat.getQuestionNum();
                    profileNum += tasteStat.getProfileNum();
                    orderNum += tasteStat.getOrderNum();
                }

                modelAndView.addObject("tasteStatList", CollectionUtils.constructMapValueFromList(tasteStatList, "statDay"));
            }
            
            modelAndView.addObject("yearMonth", DateFormatUtils.format(day, "yyyy-MM"));
            if(DateUtils.isSameMonth(day, now)) {
                modelAndView.addObject("maxDay", calendar.get(Calendar.DAY_OF_MONTH));
            } else {
                calendar.setTime(day);
                modelAndView.addObject("maxDay", calendar.getMaximum(Calendar.DATE));
            }
        }
        
        modelAndView.addObject("questionNum", questionNum);
        modelAndView.addObject("profileNum", profileNum);
        modelAndView.addObject("orderNum", orderNum);
        
        modelAndView.addObject("sources", sources);
        modelAndView.addObject("selectedSource", source);
        modelAndView.addObject("today", DateFormatUtils.format(now, "yyyy-MM-dd"));
        
        return modelAndView;
    }
    
    /**
     * 
     * @param tasteSignUpId
     * @return
     */
    @RequestMapping(value = "/{tasteSignUpId}/add-service", method = RequestMethod.GET)
    public ModelAndView addService(@PathVariable("tasteSignUpId") Long tasteSignUpId) {
        
        ModelAndView modelAndView = new ModelAndView("report/taste-add-service");
        
        modelAndView.addObject("tasteSignUpId", tasteSignUpId);
        
        return modelAndView;
    }
    
    /**
     * 
     * @param tasteSignUpId
     * @return
     */
    @RequestMapping(value = "/{tasteSignUpId}/add-service", method = RequestMethod.PATCH)
    public @ResponseBody String onAddService(@PathVariable("tasteSignUpId") Long tasteSignUpId) {
        
        Result result = new Result();
        
        try {
            TasteSignUp tasteSignUp = genericDaoSupport.load(TasteSignUp.class, tasteSignUpId);
            
            if(tasteSignUp != null && !tasteSignUp.isServiceAdded()) {
                reportService.addService(tasteSignUp);
            }
            
            result.success().message("确认已添加客服微信成功");
            
        } catch (Exception e) {
            result.fail().message("确认已添加客服微信失败");
        }
        
        return JsonUtils.toJsonString(result);
        
    }
    
    /**
     * 
     * @return
     */
    @RequestMapping(value = "/export-view", method = RequestMethod.GET)
    public ModelAndView export() {
        ModelAndView modelAndView = new ModelAndView("report/taste-stat-report-export");
        
        List<String> sources = reportService.listTasteStatSource();
        
        modelAndView.addObject("sources", sources);
        modelAndView.addObject("today", DateFormatUtils.format(new Date(), "yyyy-MM-dd"));
        
        return modelAndView;
    }
    
    /**
     * 
     * @param login
     * @param source
     * @param beginDate
     * @param endDate
     * @return
     */
    @RequestMapping(value = "/export", method = RequestMethod.GET)
    public ModelAndView onExport(@Secure Login login,
                                 @RequestParam(value="source", required=false) String source,
                                 @RequestParam(value = "beginDate") @DateTimeFormat(pattern = "yyyy-MM-dd") Date beginDate,
                                 @RequestParam(value = "endDate") @DateTimeFormat(pattern = "yyyy-MM-dd") Date endDate) {
        ModelAndView modelAndView = new ModelAndView(new ExcelTemplateView("taste-stat-report.xls"));
        
        if(StringUtils.isBlank(source)) {
            source = null;
        }
        
        if(beginDate == null || endDate == null) {
            beginDate = new Date();
            endDate = new Date();
        }
        
        int questionNum = reportService.countBMIQuestion(source, beginDate, endDate);
        int profileNum = reportService.countTasteSignUp(source, beginDate, endDate);
        int orderNum = reportService.countOrder(source, beginDate, endDate);
        
        List<TasteSignUp> tasteSignUpList = reportService.listTasteSignUp(source, beginDate, endDate);
        
        modelAndView.addObject("questionNum", questionNum);
        modelAndView.addObject("profileNum", profileNum);
        modelAndView.addObject("orderNum", orderNum);
        modelAndView.addObject("tasteSignUpList", tasteSignUpList);
        modelAndView.addObject("source", source);
        modelAndView.addObject("beginDate", DateFormatUtils.format(beginDate, "yyyy-MM-dd"));
        modelAndView.addObject("endDate", DateFormatUtils.format(endDate, "yyyy-MM-dd"));
        DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        modelAndView.addObject("fmt", fmt);
        
        return modelAndView;
    }
}
